/**
 * 将JSON字符串转换为对象
 * @param jsonString 待转换的json字符串
 * @param defaultValue 转换出错时,使用的默认值
 * @returns
 */
export function parseJSONWithDefault<T>(jsonString: string, defaultValue: T): Promise<T> {
  return new Promise((resolve, reject) => {
    try {
      const parsed = JSON.parse(jsonString);
      resolve(parsed);
    } catch {
      resolve(defaultValue);
    }
  });
}

/**
 * url参数编码
 * 传入json格式的对象
 * @param {*Object} params
 * 示例数据  window.btoa(window.encodeURIComponent(JSON.stringify({ "userCode": "20130127", "fundAccount": "20130127" })))
 *
 */
export const encryUrl = (params: Record<string, any>): string => {
  if (Object.prototype.toString.call(params) !== "[object Object]") {
    return "";
  }
  try {
    return `enData=${window.btoa(window.encodeURIComponent(JSON.stringify(params)))}`; // 编码
  } catch (err) {
    return "";
  }
};

/**
 * url参数解码
 * 传入编码后的json字符串
 * @param {*string} params
 * JSON.parse(window.decodeURIComponent(window.atob(params)))
 */
export const decryptUrl = (params: string): Record<string, any> => {
  if (typeof params !== "string") {
    return {};
  }
  try {
    return JSON.parse(window.decodeURIComponent(window.atob(params)));
  } catch (err) {
    return {};
  }
};
